package com.ruoyi.web.controller.system

import com.ruoyi.common.annotation.Log
import com.ruoyi.common.constant.UserConstants
import com.ruoyi.common.core.controller.BaseController
import com.ruoyi.common.core.domain.AjaxResult
import com.ruoyi.common.core.domain.entity.SysDept
import com.ruoyi.common.enums.BusinessType
import com.ruoyi.system.service.ISysDeptService
import org.apache.commons.lang3.ArrayUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*

/**
 * 部门信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/dept")
open class SysDeptController
    : BaseController() {

    @Autowired
    private lateinit var deptService: ISysDeptService

    /**
     * 获取部门列表
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    open fun list(dept: SysDept?): AjaxResult {
        val depts = deptService.selectDeptList(dept)
        return success(depts)
    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    open fun excludeChild(@PathVariable(value = "deptId", required = false) deptId: Long?): AjaxResult {
        val depts = deptService.selectDeptList(SysDept())
        depts.removeIf { d ->
            d.deptId === deptId || ArrayUtils.contains(
                org.apache.commons.lang3.StringUtils.split(
                    d.ancestors,
                    ","
                ), deptId.toString() + ""
            )
        }
        return success(depts)
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = ["/{deptId}"])
    open fun getInfo(@PathVariable deptId: Long?): AjaxResult {
        deptService.checkDeptDataScope(deptId)
        return success(deptService.selectDeptById(deptId))
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    open  fun add(@Validated @RequestBody dept: SysDept): AjaxResult {
        if (!deptService.checkDeptNameUnique(dept)) {
            return error("新增部门'" + dept.deptName + "'失败，部门名称已存在")
        }
        dept.createBy = username
        return toAjax(deptService.insertDept(dept))
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    open fun edit(@Validated @RequestBody dept: SysDept): AjaxResult {
        val deptId: Long? = dept.deptId
        deptService.checkDeptDataScope(deptId)
        if (!deptService.checkDeptNameUnique(dept)) {
            return error("修改部门'" + dept.deptName + "'失败，部门名称已存在")
        } else if (dept.parentId==deptId) {
            return error("修改部门'" + dept.deptName + "'失败，上级部门不能是自己")
        } else if (UserConstants.DEPT_DISABLE==dept.status && deptService.selectNormalChildrenDeptById(
                deptId
            ) > 0
        ) {
            return error("该部门包含未停用的子部门！")
        }
        dept.updateBy = username
        return toAjax(deptService.updateDept(dept))
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    open fun remove(@PathVariable deptId: Long?): AjaxResult {
        if (deptService.hasChildByDeptId(deptId)) {
            return warn("存在下级部门,不允许删除")
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return warn("部门存在用户,不允许删除")
        }
        deptService.checkDeptDataScope(deptId)
        return toAjax(deptService.deleteDeptById(deptId))
    }
}
